<?php

namespace maotool\thread;

use maotool\core\facade\Config;
use maotool\core\serializer\closure\SerializableClosure;
use maotool\file\DirUtil;
use maotool\file\FileUtil;
use maotool\util\IdUtil;
use maotool\util\PathUtil;
use Closure;

class ThreadUtil
{

    /**
     * 执行异步
     * @param $closure Closure
     * @return void
     */
    public static function execAsync($closure) {
        $uid = IdUtil::simpleUUID();
        $path = Config::get("framework.runtime.thread.path");
        $dirPath = PathUtil::path($path, "task", substr(md5($uid), 0, 2));
        $filePath = PathUtil::path($dirPath, substr(md5($uid), 2) . ".thread");
        $instance = new SerializableClosure($closure);
        $serialize = serialize($instance);
        FileUtil::write($filePath, $serialize);
    }

    /**
     * 延迟执行
     * @param $seconds
     * @return true
     */
    public static function sleep($seconds)
    {
        sleep($seconds);
        return true;
    }

}